package edu.xidian.cnmano.k8sclient;

import edu.xidian.cnmano.api.MetricsServerApi;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.util.Config;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 主要是一些 k8s api，其中CoreV1Api可以访问pod和node资源，AppsV1Api可以访问deployment资源，MetricsServerApi可以访问node中cpu和
 * 内存的使用情况，弥补CoreV1Api的不足
 *
 * @author zhr
 * @date 2020/11/17-14:05
 */
@Component
public class ClusterApis {

    @Value("${k8s-cluster-ip}")
    private String K8S_CLUSTER_IP;

    @Bean
    public CoreV1Api coreV1Api() throws IOException {
        ApiClient client = Config.defaultClient();
        client.setBasePath(K8S_CLUSTER_IP);
        return new CoreV1Api(client);
    }

    @Bean
    public CoreV1Api coreWatchV1Api() throws IOException {
        ApiClient client = Config.defaultClient();
        client.setBasePath(K8S_CLUSTER_IP);
        OkHttpClient httpClient =
                client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
        client.setHttpClient(httpClient);
        return new CoreV1Api(client);
    }

    @Bean
    public AppsV1Api appsV1Api() throws IOException {
        ApiClient client = Config.defaultClient();
        client.setBasePath(K8S_CLUSTER_IP);
        return new AppsV1Api(client);
    }

    @Bean
    public AppsV1Api appsV1WatchApi() throws IOException {
        ApiClient client = Config.defaultClient();
        client.setBasePath(K8S_CLUSTER_IP);
        OkHttpClient httpClient =
                client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
        client.setHttpClient(httpClient);
        return new AppsV1Api(client);
    }

    @Bean
    public MetricsServerApi metricsServerApi() throws IOException {
        ApiClient client = Config.defaultClient();
        client.setBasePath(K8S_CLUSTER_IP);
        return new MetricsServerApi(client);
    }
}
